package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.entry.Category;
import com.itheima.pojo.R;
import com.itheima.service.CategoryService;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @PostMapping
    public R<String> add(@RequestBody Category category){
        categoryService.save(category);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page> page(Integer page,Integer pageSize){
        Page<Category> categoryPage = new Page<>(page,pageSize);
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = new LambdaQueryWrapper<>();
        categoryLambdaQueryWrapper.orderByDesc(Category::getType);
     categoryService.page(categoryPage, categoryLambdaQueryWrapper);
        return R.success(categoryPage);
    }

    @DeleteMapping
    public R<String> remove(Long id){
        categoryService.remove(id);
        return R.success("删除成功");
    }

    @GetMapping("/list")
    public R<List> list(Category category){
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(category.getType() != null,Category::getType,category.getType());
        wrapper.orderByDesc(Category::getSort);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }

    @PutMapping
    public R<String> upDate(@RequestBody Category category){

        categoryService.updateById(category);

        return R.success("修改成功");
    }
}
